package dnl.proj.rami;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL;

/**
 * @author Daniel Orr
 */
public class RamisTrickApp {

    Robot robot;
    GroovyTextManipulationExecutor executor;

    StringConversion sc = new Conversion2();

    public RamisTrickApp() {
        executor = new GroovyTextManipulationExecutor();

        initTrayIcon();

        JIntellitype.getInstance();
        JIntellitype.getInstance().registerHotKey(1, JIntellitype.MOD_WIN, (int) 'A');
        JIntellitype.getInstance().registerHotKey(121, 0, 121);
        JIntellitype.getInstance().addHotKeyListener(new HotkeyListener() {
            @Override
            public void onHotKey(int keyCode) {
                if(keyCode == 121) {
                    ctrlA();
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    applyConversionAction();
                }
                else {
                    applyConversionAction();
                }
            }
        });
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    private void applyConversionAction() {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();
        try {
            copyInput();
            String clipboardContents = getClipboardContents(clipboard);
            Thread.sleep(300);
            clipboardContents = getClipboardContents(clipboard);
            System.out.println("in:\n"+clipboardContents);
            final String reversedWords = sc.convert(clipboardContents);
            System.out.println("out:\n"+reversedWords+"\n");
            StringSelection strSel = new StringSelection(reversedWords);
            clipboard.setContents(strSel, null);
            pasteOutput();
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getClipboardContents(Clipboard clipboard) throws UnsupportedFlavorException, IOException {
        try {
            return (String) clipboard.getData(DataFlavor.stringFlavor);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private void initTrayIcon() {
        final PopupMenu popup = new PopupMenu();
        final URL url = getClass().getResource("rami.png");
        ImageIcon ii = new ImageIcon(url);
        final TrayIcon trayIcon = new TrayIcon(ii.getImage(), "");
        final SystemTray tray = SystemTray.getSystemTray();
        MenuItem exitItem = new MenuItem("Exit");

        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });

        popup.add(exitItem);
        trayIcon.setPopupMenu(popup);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }
    }

    private void copyInput() {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

    private void ctrlA() {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_A);
        robot.keyRelease(KeyEvent.VK_A);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

    private void pasteOutput() {
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }

//    public String reverseEachWord(String s){
//        final String[] words = StringUtils.split(s, " ");
//        StringBuilder sb = new StringBuilder();
//        for (String word : words) {
//            final String reversed = StringUtils.reverse(word);
//            sb.append(reversed);
//            sb.append(" ");
//        }
//        return sb.toString();
//    }

    public static void main(String[] args) {
        if (JIntellitype.checkInstanceAlreadyRunning("Ramis")) {
            System.err.println("An instance of this application is already running");
            System.exit(1);
        }
        final RamisTrickApp ramisTrickApp = new RamisTrickApp();
    }
}
